import { getToken, setToken, removeToken } from '@/utils/auth'
import { getLoginService, getUserInfoEervice } from '@/api/user'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  token: getToken(), // token初始值，首先从getToken中读取
  title: '登录',
  count: 100,
  userInfo: {} ,//用户基本资料
  routes: constantRoutes //初始值，静态路由的数组
}
const mutations = {
  setToke(state, newToke) {
    state.token = newToke
    setToken(newToke) // 需要将vuex中的数据（token）同步到缓存
  },
  changeInfo(state) {
    state.title = '注册'
    state.count = state.count + 1
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 存储用户基本资料
  setUserInfo(state, newUserInfo) {
     state.userInfo = newUserInfo
  },
  setRoutes(state, newRoutes) {
     state.routes = [...constantRoutes, ...newRoutes]
  }
}
const actions = {
  async login(context, data) {
  const token = await getLoginService({
      mobile: data.username,
      password: data.password
    })
    context.commit('setToke', token)
  },
  async getUserInfo(context){
   const res = await getUserInfoEervice()
   context.commit('setUserInfo', res)
   return res //返回数据
  }, 
  // 退出登录 删除 用户信息
  loginOut(context){
    context.commit('setUserInfo', {}) //删除用户信息.传入空对象
    context.commit('removeToken') //删除token
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
